<?php
namespace app\api\controller\v1\controller\distance;

use app\api\controller\v1\model\distance\Distance as Di;
use think\Controller;
use app\api\controller\Api;
use think\Model;
use think\Db;
use think\Image;
use think\Request;
use JPush\Client as JPush;
use think\Response;
use app\api\controller\UnauthorizedException;
use think\Validate;


class Distance extends api
{

    //GPS返回周围$distance范围内的用户 json
    public function GetRange($latitude,$longitude,$distance,$type = ""){

        $petinfo = array();
        $m = Db::connect("db_mongo")->table("yunmiao_location")->where(['loc' => ['near',[floatval($longitude),floatval($latitude),intval($distance)*1000]]] )->select();

        foreach ($m as $k =>$v) {
            $user_id = $m[$k]['user_id'];
            //判断是否被注销
            try{
                $is_cancel = Db::name("ym_cancel")->where('user_id','=',$user_id)->find();
            }catch(\Exception $e){
                return $this->returnmsg(410,'查询数据库崩溃');
            }
            if($is_cancel['status'] == 1)
            {
                continue;
            }

            //判断宠物数据存在，且通过认证permisstion_to_access值为1
            $has_pet = Db::query("select pet_id from ym_pet where user_id = ".$user_id." and permisstion_to_access = 1");
            if(!is_array($has_pet) || count($has_pet) == 0)
            {
                continue;
            }
            //判断是否约宠，是否寄样，宠物种类
            $result = Db::query("select a.pet_icon,a.pet_kind,b.pet_type,b.share_pet_agree_or_not,b.appointment_or_not from ym_pet as a join user_info as b on a.user_id = b.user_id  where a.user_id = '$user_id'");
            if($type == "appointment" && $result[0]['appointment_or_not'] ==1)
            {
                $m[$k]['pet_info'] = $result[0];
                $petinfo[] = $m[$k];
            }else if($type == "forsterage" && $result[0]['fosterage_or_not'] ==1)
            {
                $m[$k]['pet_info'] = $result[0];
                $petinfo[] = $m[$k];
            }else if($type == $result[0]['pet_kind'])
            {
                $m[$k]['pet_info'] = $result[0];
                $petinfo[] = $m[$k];
            }else if($type == '')
            {
                $m[$k]['pet_info'] = $result[0];
                $petinfo[] = $m[$k];
            }
           // if($result[0]['share_pet_agree_or_not'] != 1 || ($type != '' && $type != $result[0]['pet_kind']) || $result[0]['appointment_or_not'] !=1)
           // {
           //     continue;
           // }
        }
        return json($petinfo);
    }


    //显示附近的人
    public function nearby_users($latitude,$longitude,$distance,$pageno){
        $pagesize = 20;
        $startno = $pageno *$pagesize;

        $m = Db::connect("db_mongo")->table("yunmiao_location")->where(['loc' => ['near',[floatval($longitude),floatval($latitude),intval($distance)*1000]]])->limit($startno,$pagesize)->order('distances','asc')->select();


        foreach ($m as $k =>$v) {
            // $user_id = $v['user_id'];
            $user_id = $m[$k]['user_id'];
            $longitude1 =  $m[$k]['loc']['coordinates'][0];
            $latitude1 =  $m[$k]['loc']['coordinates'][1];

            //判断是否被注销
            try{
                $is_cancel = Db::name("ym_cancel")->where('user_id','=',$user_id)->find();
            }catch(\Exception $e){
                return $this->returnmsg(410,'查询数据库崩溃');
            }
            if($is_cancel['status'] == 1)
            {
                continue;
            }

            $result = Db::query("select user_id,user_name,user_icon,user_desc,appointment_or_not from user_info where user_id = '$user_id'");


            $distances = $this->calculate_distance($latitude, $longitude, $latitude1, $longitude1)*1000;
            if ($distances < 100) {
                $distances = 100;
            }
            if (!empty($result)) {
                $arr[] = ['user_info'=>$result[0],'distances'=>$distances];
            }

        }
        if (!empty($arr)) {
            $user = $this->f_order($arr,'distances',1);
            return $this->returnmsg(200,'附近的人',$user);
        }else{
            return $this->returnmsg(200,'附近没有用户');
        }

    }

//判断距离
    public function f_order($arr,$field,$sort){
        $order = array();
        foreach($arr as $kay => $value){
            $order[] = $value[$field];
        }
        if($sort==1){
            array_multisort($order,SORT_ASC,$arr);
        }else{
            array_multisort($order,SORT_DESC,$arr);
        }
        return $arr;
    }



    //插入用户
    public function insert_map($latitude,$longitude,$user_id){

        $m = Di::getInsertMap($latitude,$longitude,$user_id);

        if ($m) {
            return $this->returnmsg(200,'获取成功');
        }else{
            return $this->returnmsg(500,'获取失败');
        }
    }



//计算距离
    public function calculate_distance($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon){
        $fEARTH_RADIUS = 6378137;
        //角度换算成弧度
        $fRadLon1 = deg2rad($fP1Lon);
        $fRadLon2 = deg2rad($fP2Lon);
        $fRadLat1 = deg2rad($fP1Lat);
        $fRadLat2 = deg2rad($fP2Lat);
        //计算经纬度的差值
        $fD1 = abs($fRadLat1 - $fRadLat2);
        $fD2 = abs($fRadLon1 - $fRadLon2);
        //距离计算
        $fP = pow(sin($fD1/2), 2) +
            cos($fRadLat1) * cos($fRadLat2) * pow(sin($fD2/2), 2);
        return round(floatval($fEARTH_RADIUS * 2 * asin(sqrt($fP))/1000),2);
    }


//广告图片
    public function get_ads_img(){
      $img = Di::getAdsImg();
        return $img;
    }

    //

















}